<template>
  <div class="chat-container-fullscreen">
    <div class="chat-header">
      <div class="chat-title">
        <span>课程反馈与建议 - 课程ID: {{ courseId }}</span>
      </div>
      <div class="header-actions">
        <el-button 
          type="primary" 
          size="small"
          @click="$router.go(-1)"
        >
          返回
        </el-button>
      </div>
    </div>

    <div class="chat-messages-container">
      <div class="chat-messages" ref="chatBoxRef">
        <div 
          v-for="(message, index) in messages" 
          :key="index"
          :class="['message-wrapper', message.role]"
        >
          <div class="avatar">
            <img 
              v-if="message.role === 'assistant'" 
              src="../../assets/ktzlfxs.jpg" 
              alt="AI"
              @error="handleAvatarError($event, 'assistant')"
            >
            <img 
              v-else 
              src="../../assets/user-avatar.svg" 
              alt="User"
              @error="handleAvatarError($event, 'user')"
            >
          </div>
          <div class="message-content">
            <div class="message-text" v-html="formatMessageContent(message.content)"></div>
            <span v-if="loading && index === messages.length - 1" class="cursor"></span>
          </div>
        </div>
      </div>
    </div>

    <div class="chat-input">
      <el-input
        v-model="userInput"
        type="textarea"
        :rows="3"
        placeholder="请输入您的问题..."
        :disabled="loading"
        @keydown="handleKeydown"
        class="input-box"
      />
      <el-button 
        type="primary"
        :disabled="!userInput.trim() || loading"
        @click="sendMessage"
        class="send-button"
      >
        发送
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, onBeforeUnmount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

interface Message {
  role: 'user' | 'assistant'
  content: string
}

const route = useRoute()
const router = useRouter()
const courseId = ref<string | null>(null)
const messages = ref<Message[]>([])
const loading = ref(false)
const chatBoxRef = ref<HTMLDivElement | null>(null)
const userInput = ref('')
let eventSource: EventSource | null = null

// 处理头像加载错误
const handleAvatarError = (event: Event, type: string) => {
  const target = event.target as HTMLImageElement
  target.style.display = 'none'
  const parent = target.parentNode as HTMLElement
  
  if (type === 'assistant') {
    parent.innerHTML = '<div class="text-avatar">AI</div>'
  } else {
    parent.innerHTML = '<div class="text-avatar">用户</div>'
  }
}

// 格式化消息内容，支持纯文本
const formatMessageContent = (content: string): string => {
  if (!content) return ''
  // 暂时使用纯文本显示以避免marked库的兼容性问题
  return content
  // 如果需要Markdown支持，请在确保marked库正常工作后使用以下代码
  /*
  try {
    const parsed = marked.parse(content)
    return typeof parsed === 'string' ? DOMPurify.sanitize(parsed) : content
  } catch (error) {
    console.error('渲染Markdown失败:', error)
    return content
  }
  */
}

// 滚动到聊天底部
const scrollToBottom = async () => {
  await nextTick()
  if (chatBoxRef.value) {
    chatBoxRef.value.scrollTop = chatBoxRef.value.scrollHeight
  }
}

// 发送用户消息并获取AI回复
const sendMessage = async () => {
  const trimmedInput = userInput.value.trim()
  if (!trimmedInput || loading.value) return
  
  // 添加用户消息到聊天
  messages.value.push({
    role: 'user',
    content: trimmedInput
  })
  
  // 清空输入框
  userInput.value = ''
  
  // 滚动到底部
  await scrollToBottom()
  
  // 准备接收AI回复
  loading.value = true
  
  // 创建AI响应占位符
  messages.value.push({
    role: 'assistant',
    content: ''
  })
  
  // 滚动到底部
  await scrollToBottom()
  
  // 启动SSE连接，获取流式回复
  startSSEConnection(trimmedInput)
}

// 启动SSE连接
const startSSEConnection = (userMessage: string) => {
  if (!courseId.value) {
    ElMessage.warning('课程ID缺失，无法获取反馈')
    loading.value = false
    return
  }
  
  if (eventSource) {
    eventSource.close()
    eventSource = null
  }
  
  // 创建SSE连接
  const apiUrl = `/api/ai-api/chat/stream/${courseId.value}?message=${encodeURIComponent(userMessage)}`
  console.log('开始连接:', apiUrl)
  eventSource = new EventSource(apiUrl)
  
  // 处理接收到的消息
  eventSource.onmessage = (event) => {
    try {
      console.log('收到SSE消息:', event.data)
      const data = JSON.parse(event.data)
      const content = data?.choices?.[0]?.delta?.content
      
      if (content) {
        // 将内容追加到最后一条AI消息
        const lastMessage = messages.value[messages.value.length - 1]
        if (lastMessage && lastMessage.role === 'assistant') {
          lastMessage.content += content
          nextTick(() => {
            scrollToBottom()
          })
        }
      }
    } catch (err) {
      console.warn('解析SSE数据失败:', err)
    }
  }
  
  // 处理流式输出完成事件
  eventSource.addEventListener('complete', () => {
    console.log('SSE连接完成')
    loading.value = false
    eventSource?.close()
  })
  
  // 处理错误
  eventSource.onerror = (err) => {
    console.error('SSE连接错误:', err)
    ElMessage.error('AI分析失败或连接中断')
    loading.value = false
    eventSource?.close()
  }
}

// 初始欢迎消息
const initWelcomeMessage = () => {
  // 不显示欢迎消息
  messages.value = []
}

// 组件挂载
onMounted(() => {
  const recordId = route.query.recordId
  if (recordId && typeof recordId === 'string') {
    courseId.value = recordId
    initWelcomeMessage()
    // 自动启动分析，无需等待用户输入
    startChatAnalysis()
  } else {
    ElMessage.warning('未提供课程ID')
    router.push('/tabus/classroom-analysis-records')
  }
})

// 自动启动课程分析
const startChatAnalysis = () => {
  if (!courseId.value) {
    ElMessage.warning('课程ID缺失，无法获取反馈')
    return
  }
  
  // 准备接收AI回复
  loading.value = true
  
  // 创建AI响应占位符
  messages.value.push({
    role: 'assistant',
    content: ''
  })
  
  // 启动SSE连接，获取分析结果
  if (eventSource) {
    eventSource.close()
    eventSource = null
  }
  
  console.log('开始连接:', `/api/ai-api/chat/stream/${courseId.value}`)
  
  // 创建SSE连接 - 直接连接不带message参数进行初始分析
  const apiUrl = `/api/ai-api/chat/stream/${courseId.value}`
  eventSource = new EventSource(apiUrl)
  
  // 处理接收到的消息
  eventSource.onmessage = (event) => {
    try {
      console.log('收到SSE消息:', event.data)
      const data = JSON.parse(event.data)
      const content = data?.choices?.[0]?.delta?.content
      
      if (content) {
        // 将内容追加到最后一条AI消息
        const lastMessage = messages.value[messages.value.length - 1]
        if (lastMessage && lastMessage.role === 'assistant') {
          lastMessage.content += content
          nextTick(() => {
            scrollToBottom()
          })
        }
      }
    } catch (err) {
      console.warn('解析SSE数据失败:', err)
    }
  }
  
  // 处理流式输出完成事件
  eventSource.addEventListener('complete', () => {
    console.log('SSE连接完成')
    loading.value = false
    eventSource?.close()
  })
  
  // 处理错误
  eventSource.onerror = (err) => {
    console.error('SSE连接错误:', err)
    ElMessage.error('AI分析失败或连接中断')
    loading.value = false
    eventSource?.close()
  }
}

// 处理键盘事件
const handleKeydown = (event: KeyboardEvent) => {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault()
    sendMessage()
  }
}

// 组件销毁前关闭SSE连接
onBeforeUnmount(() => {
  if (eventSource) {
    eventSource.close()
    eventSource = null
  }
})
</script>

<style scoped>
.chat-container-fullscreen {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f7f9fc;
  z-index: 1000;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: linear-gradient(to right, #409EFF, #53a8ff);
  color: white;
  padding: 12px 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.chat-title {
  font-size: 18px;
  font-weight: bold;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.chat-messages-container {
  flex: 1;
  overflow: hidden;
  padding: 20px;
}

.chat-messages {
  height: 100%;
  overflow-y: auto;
  padding: 0 10px;
}

.message-wrapper {
  display: flex;
  margin-bottom: 24px;
  align-items: flex-start;
}

.message-wrapper.user {
  flex-direction: row-reverse;
}

.avatar {
  width: 38px;
  height: 38px;
  border-radius: 50%;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.user .avatar {
  background-color: #67c23a;
  margin-left: 16px;
}

.assistant .avatar {
  background-color: #409EFF;
  margin-right: 16px;
}

.text-avatar {
  color: white;
  font-size: 14px;
  font-weight: bold;
}

.message-content {
  max-width: 80%;
  padding: 12px 18px;
  border-radius: 18px;
  position: relative;
  color: #000 !important;
}

.user .message-content {
  background: linear-gradient(135deg, #67c23a, #85ce61);
  color: #000 !important;
  border-top-right-radius: 4px;
  text-align: right;
}

.assistant .message-content {
  background-color: white;
  border: 1px solid #ebeef5;
  border-top-left-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  color: #000 !important;
}

.message-text {
  word-break: break-word;
  line-height: 1.6;
  white-space: pre-wrap;
  color: #000 !important;
}

/* 支持markdown渲染样式 */
.message-text :deep(code) {
  background-color: rgba(0, 0, 0, 0.05);
  padding: 0.2em 0.4em;
  border-radius: 3px;
  font-family: monospace;
}

.message-text :deep(pre) {
  background-color: #f3f4f5;
  padding: 10px;
  border-radius: 5px;
  overflow-x: auto;
}

.message-text :deep(a) {
  color: #409EFF;
}

.user .message-text :deep(a) {
  color: #fff;
}

.cursor {
  display: inline-block;
  width: 8px;
  height: 16px;
  background-color: #333;
  animation: blink 1s step-end infinite;
  margin-left: 2px;
  vertical-align: middle;
}

.user .cursor {
  background-color: white;
}

.chat-input {
  padding: 16px 20px;
  background-color: white;
  border-top: 1px solid #ebeef5;
  display: flex;
  gap: 16px;
  align-items: flex-end;
}

.input-box {
  flex: 1;
}

.input-box :deep(.el-textarea__inner) {
  border-radius: 12px;
  padding: 12px;
  resize: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
}

.input-box :deep(.el-textarea__inner:focus) {
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.send-button {
  border-radius: 12px;
  padding: 12px 24px;
  height: auto;
  min-width: 100px;
}

@keyframes blink {
  from, to {
    opacity: 1;
  }
  50% {
    opacity: 0;
  }
}

@media (max-width: 768px) {
  .message-content {
    max-width: calc(90% - 38px);
  }
  
  .chat-input {
    padding: 10px;
  }
  
  .send-button {
    min-width: 80px;
    padding: 12px;
  }
}
</style>
